package com.csu54sher.basereservation.controller;

import com.csu54sher.basereservation.common.ApiResponse;
import com.csu54sher.basereservation.constant.ExceptionConstant;
import com.csu54sher.basereservation.dto.UserDTO;
import com.csu54sher.basereservation.dto.UserLoginDTO;
import com.csu54sher.basereservation.dto.UserPasswordDTO;
import com.csu54sher.basereservation.dto.UserWithoutPasswordDTO;
import com.csu54sher.basereservation.entity.College;
import com.csu54sher.basereservation.entity.User;
import com.csu54sher.basereservation.exception.NoCollegeException;
import com.csu54sher.basereservation.properties.JWTproperties;
import com.csu54sher.basereservation.service.ICollegeService;
import com.csu54sher.basereservation.service.IUserService;
import com.csu54sher.basereservation.util.JWTUtil;
import com.csu54sher.basereservation.util.ThreadLocalUtil;
import com.csu54sher.basereservation.vo.UserVO;
import com.csu54sher.basereservation.vo.UserWithoutTokenVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author csu54sher
 * @since 2025-10-19
 */
@RestController
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private IUserService userService;

    @Autowired
    private JWTproperties jwtproperties;

    @Autowired
    private ICollegeService collegeService;


    /**
     * 登录
     * @param userLoginDTO
     * @return
     * @author liuke
     */
    @PostMapping("/login")
    public ApiResponse<UserVO> login(@RequestBody UserLoginDTO userLoginDTO) {

        User user = userService.login(userLoginDTO);

        // 登录成功，生成 token
        String token = JWTUtil.createToken(
                jwtproperties.getSecretKey(),
                jwtproperties.getTtl(),
                userLoginDTO.getIdNumber());

        log.info("用户 {} 登录成功，生成 token：{}", user.getIdNumber(), token);
        // 获取学院名称
        College college = collegeService.getById(user.getCollegeId());
        String collegeName = college.getName();
        if(collegeName == null){
            throw new NoCollegeException(ExceptionConstant.NO_COLLEGE_EXCEPTION);
        }

        UserVO userVO = UserVO.builder()
                .id(user.getId())
                .name(user.getName())
                .nickname(user.getNickname())
                .idNumber(user.getIdNumber())
                .college(collegeName)
                .department(user.getDepartment())
                .phoneNumber(user.getPhoneNumber())
                .isAdmin(user.getIsAdmin())
                .token(token)
                .build();

        return ApiResponse.success(userVO);
    }


    /**
     *  注册
     * @param userDTO
     * @return
     * @author liuke
     */
    @PostMapping("/register")
    public ApiResponse register(@RequestBody UserDTO userDTO) {
        userService.register(userDTO);
        return ApiResponse.success();
    }


    /**
     * 获取当前登录用户信息
     * @return
     * @author liuke
     */
    @GetMapping("/user")
    public ApiResponse<UserWithoutTokenVO> getUserInfo() {
        // 获取当前用户学号或者工号
        String currentId = ThreadLocalUtil.getCurrentId();
        User user = userService.query().eq("id_number", currentId).one();
        String collegeName = collegeService.query().eq("id", user.getCollegeId()).one().getName();
        UserWithoutTokenVO userWithoutTokenVO = UserWithoutTokenVO.builder()
                .id(user.getId())
                .name(user.getName())
                .nickname(user.getNickname())
                .idNumber(user.getIdNumber())
                .college(collegeName)
                .department(user.getDepartment())
                .phoneNumber(user.getPhoneNumber())
                .isAdmin(user.getIsAdmin())
                .build();
        return ApiResponse.success(userWithoutTokenVO);
    }

    /**
     * 修改用户信息，不修改密码
     * @param userWithoutPasswordDTO
     * @return
     * @author liuke
     */
    @PutMapping("/user")
    public ApiResponse updateUserInfo(@RequestBody UserWithoutPasswordDTO userWithoutPasswordDTO) {
        // 获取当前用户学号或者工号
        String currentId = ThreadLocalUtil.getCurrentId();
        userService.updateUserInfo(userWithoutPasswordDTO, currentId);
        return ApiResponse.success();
    }

    /**
     * 修改用户密码
     * @param userpasswordDTO
     * @return
     * @author liuke
     */
    @PutMapping("/user/password")
    public ApiResponse updateUserPassword(@RequestBody UserPasswordDTO userpasswordDTO) {
        // 获取当前用户学号或者工号
        String currentId = ThreadLocalUtil.getCurrentId();
        userService.updateUserPassword(userpasswordDTO, currentId);
        return ApiResponse.success();
    }

    /**
     * 退出登录
     * @return
     * @author liuke
     */
    @PostMapping("/logout")
    public ApiResponse logout() {
        ThreadLocalUtil.remove();
        return ApiResponse.success();
    }
}
